package org.example.leetcpde;

import org.junit.jupiter.api.Test;

public class reverseKGroup
        implements IListNode {
    @Test
    void reverseKGroup() {
        ListNode fill = new ListNode().fill("[1,2,3,4,5]");
        ListNode revert = reverseKGroup(fill, 2);
        System.out.println(revert);
    }

    public ListNode reverseKGroup(ListNode head,
                                  int k) {
        ListNode root = new ListNode(0, head), res = root, it = head;

        out:
        while (head != null) {
            for (int i = 0; i < k - 1; i++) {
                it = it.next;
                if (it == null) {
                    res.next = head;
                    break out;
                }
            }

            ListNode[] reverse = reverse(head, it);
            ListNode h = reverse[0], t = reverse[1];
            res.next = h;
            res = t;

            head = it = t.next;
        }

        return root.next;
    }

    ListNode[] reverse(ListNode head,
                       ListNode tail) {
        for (ListNode h = head, t = tail.next, stop = tail.next; h != stop; ) {
            ListNode next = h.next;
            h.next = t;
            t = h;
            h = next;
        }

        return new ListNode[]{tail, head};
    }
}
